package com.base.boot.demo.config.security;

import com.base.boot.demo.config.security.handler.AppAccessDeniedHandler;
import com.base.boot.demo.config.security.handler.AppAuthenticationFailureHandler;
import com.base.boot.demo.config.security.handler.AppAuthenticationSuccessHandler;
import com.base.boot.demo.config.security.provider.UserAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

@Configuration
@EnableResourceServer
public class AppResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Autowired
    UserAuthenticationProvider userAuthenticationProvider;

    @Autowired
    AppAccessDeniedHandler appAccessDeniedHandler;

    @Autowired
    AppAuthenticationSuccessHandler appAuthenticationSuccessHandler;

    @Autowired
    AppAuthenticationFailureHandler appAuthenticationFailureHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        System.out.println("初始化security认证配置。。。");
        http
                .exceptionHandling()
                .accessDeniedHandler(appAccessDeniedHandler)
                .and()
                .authenticationProvider(userAuthenticationProvider)
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/error.html", "/noe4j/**").permitAll()
                .antMatchers("/js/**", "/css/**", "/font/**").permitAll()
                .antMatchers("/security/user").access("hasAnyRole('ADMIN', 'USER')")
                .antMatchers("/security/admin").access("hasAnyRole('ADMIN') or hasAnyAuthority('admin_delegate')")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.html").permitAll()
                .successHandler(appAuthenticationSuccessHandler)
                .failureHandler(appAuthenticationFailureHandler)
                .loginProcessingUrl("/login").permitAll()
                .and()
                .logout().permitAll();
    }
}
